<route lang="json5">
{
  needLogin: true,
  style: {
    navigationBarTitleText: '任务详情',
  },
}
</route>

<template>
  <view class="add m-20rpx">
    <wd-form v-if="model" ref="form" :model="model">
      <wd-cell-group class="top p-20rpx bg-[#fff] border-rd-10rpx">
        <!-- 任务名称 -->
        <wd-input label="任务名称" prop="taskName" :readonly="!editYn" v-model="model.taskName" />
        <!-- 🧵🧵🧵 线 🧵🧵🧵 -->
        <view class="border-t-solid border-t-1rpx border-t-[#F3F3F3] ml-30rpx"></view>
        <!-- 截止时间 -->
        <wd-datetime-picker
          :readonly="!editYn"
          v-model="model.deadline"
          :minDate="minDate"
          :displayFormat="displayFormat"
          prop="deadline"
          label="截止时间"
        />
        <!-- 🧵🧵🧵 线 🧵🧵🧵 -->
        <view class="border-t-solid border-t-1rpx border-t-[#F3F3F3] ml-30rpx"></view>
        <!-- 任务设置 -->
        <view class="flex items-center justify-between px-24rpx">
          <text class="task-setting inline-block py-20rpx">任务设置</text>
          <view class="flex items-center">
            <text class="text-[#999] text-22rpx mr-12rpx">{{ model.status }}</text>
            <wd-switch
              v-model="model.status"
              size="small"
              active-value="开启"
              inactive-value="关闭"
              active-color="#3670F7"
              inactive-color="#F73A4A"
              :disabled="!editYn"
            />
          </view>
        </view>
        <!-- 🧵🧵🧵 线 🧵🧵🧵 -->
        <view class="border-t-solid border-t-1rpx border-t-[#F3F3F3] ml-30rpx"></view>
        <!-- 任务描述 -->
        <wd-textarea
          v-model="model.description"
          :readonly="!editYn"
          placeholder="请输入"
          label="任务描述"
        />
        <!-- 图片 -->
        <view v-if="model.imgList && model.imgList.length > 0 && !editYn">
          <view
            class="imgList"
            :class="[
              model.imgList.length > 2
                ? 'grid-cols-3 h-200rpx'
                : model.imgList.length === 2
                  ? 'grid-cols-2 h-300rpx'
                  : 'grid-cols-1 h-400rpx',
            ]"
          >
            <view
              class="images relative"
              :hover-class="editYn ? 'images-hover' : ''"
              v-for="(item, index) in model.imgList"
              :key="index"
            >
              <wd-icon name="close" size="22rpx" @click="model.imgList.splice(index, 1)"></wd-icon>
              <wd-img :src="item" :enable-preview="true" class="w-full h-full" />
            </view>
          </view>
        </view>
        <!-- 图片上传 -->
        <view class="upload" v-if="editYn">
          <wd-upload v-model:file-list="model.imgList" multiple action="/resource/oss/upload">
            <wd-img :src="uploadImgPng" class="w-full h-200rpx" />
          </wd-upload>
        </view>
      </wd-cell-group>
      <!-- 附件 -->
      <wd-cell-group class="bottom p-20rpx bg-[#fff] border-rd-10rpx mt-20rpx">
        <view class="flex items-center justify-between">
          <text class="annex">附件</text>
        </view>
        <view v-if="editYn" class="text-[#999999] text-20rpx mt-12rpx ml-20rpx">
          <text class="text-[#FF0000] fw-700 text-26rpx">*</text>
          <text>支持扩展名：png,jpg,jpeg,svg,doc,docx,xls,xlsx,pdf</text>
        </view>
        <!-- 🧵🧵🧵 线 🧵🧵🧵 -->
        <view class="border-t-solid border-t-1rpx border-t-[#F3F3F3] mt-20rpx mb-30rpx"></view>
        <!-- 测试代码 -->
        <view v-if="model.attachmentList.length > 0" class="upload-file">
          <!-- 已上传文件列表 -->
          <view
            v-for="(file, index) in model.attachmentList"
            :key="index"
            @click="handlePreviewFile(file)"
          >
            <view class="item-image relative">
              <!-- 文件类型 - 图片 -->
              <image
                class="w-full h-full"
                :src="getFileTypeImage(file.name.split('.').pop().toLowerCase())"
                mode="scaleToFill"
              />
              <!-- 删除 - 图片 -->
              <wd-img
                v-if="editYn"
                :src="uploadDelPng"
                size="30rpx"
                class="upload-delete"
                @click.stop="handleRemoveFile(index)"
              />
            </view>
            <!-- 文件名称 - 不要后缀 -->
            <view class="fileName">
              {{ file.name.split('.').slice(0, -1).join('.') }}
            </view>
          </view>
          <!-- 上传附件 -->
          <lsj-upload
            v-if="editYn && model.attachmentList.length < filesInfo.count"
            ref="lsjUpload"
            childId="upload2"
            width="150rpx"
            height="190rpx"
            position="static"
            :formats="filesInfo.formats"
            :option="filesInfo.option"
            :size="filesInfo.size"
            :count="filesInfo.count"
            :debug="filesInfo.debug"
            :instantly="filesInfo.instantly"
            @changeFile="onChange"
            @uploadEnd="onUploadEnd"
          >
            <image class="w-150rpx h-150rpx mr-8rpx" :src="uploadFilePng" mode="scaleToFill" />
            <view class="text-[#3670F7] text-22rpx text-center mt-12rpx">上传附件</view>
          </lsj-upload>
        </view>
        <!-- 暂无附件 -->
        <view class="empty" v-else>
          <wd-status-tip :image="emptyImage" tip="暂无附件" />
        </view>
        <!-- 测试代码 -->
      </wd-cell-group>
      <view class="footer">
        <wd-button size="large" :disabled="!state.bottomBtnDisabled" @click="handleEdit" block>
          {{ btnText }}
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store'
import { useToast } from 'wot-design-uni'
/* 引入 图片 上传附件 */
import uploadFilePng from '@/static/images/course/task/task-upload-file.png'
import uploadImgPng from '@/static/images/course/task/task-upload-img.png'
// eslint-disable-next-line import/no-duplicates
import docx from '@/static/images/task/word.png'
// eslint-disable-next-line import/no-duplicates
import doc from '@/static/images/task/word.png'
// eslint-disable-next-line import/no-duplicates
import xls from '@/static/images/task/excel.png'
// eslint-disable-next-line import/no-duplicates
import xlsx from '@/static/images/task/excel.png'
// eslint-disable-next-line import/no-duplicates
import jpg from '@/static/images/task/img.png'
// eslint-disable-next-line import/no-duplicates
import jpeg from '@/static/images/task/img.png'
// eslint-disable-next-line import/no-duplicates
import png from '@/static/images/task/img.png'
// eslint-disable-next-line import/no-duplicates
import svg from '@/static/images/task/img.png'
import pdf from '@/static/images/task/pdf.png'
// eslint-disable-next-line import/no-duplicates
import ppt from '@/static/images/task/ppt.png'
// eslint-disable-next-line import/no-duplicates
import pptx from '@/static/images/task/ppt.png'
import uploadDelPng from '@/static/images/task/upload-delete.png'
/* 引入 暂无数据 - 图片 */
import emptyImage from '@/static/images/icons/empty.png'
/* 引入 接口 */
import { getTaskDetails, updateTaskApi } from '@/service/edu/task/index'

const { success: showSuccess } = useToast()

const model = reactive<{
  taskName: string
  deadline: number | string
  status: any
  description: string
  imgList: any
  attachmentList: any[]
  courseId: number | string
  courseName: string
}>({
  taskName: '',
  deadline: '',
  status: false,
  description: '',
  imgList: [],
  attachmentList: [],
  courseId: '',
  courseName: '',
})

/* 最小日期 */
const minDate = new Date().getTime()

const userStore = useUserStore()

const state = reactive<{
  taskId: number | string
  courseId: number | string
  courseName: string
  bottomBtnDisabled: boolean
}>({
  taskId: '',
  courseId: '',
  courseName: '',
  bottomBtnDisabled: false,
})

const filesInfo = reactive<{
  option: any
  size: number
  count: number
  debug: boolean
  instantly: boolean
  formats: string
}>({
  // 上传接口参数
  option: {
    // 上传服务器地址
    url: import.meta.env.VITE_UPLOAD_BASEURL, // 接口地址
    // 上传附件的key
    name: 'file',
    // 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
    header: {
      Authorization: `Bearer ${userStore.userInfo.token}`,
      clientId: `${userStore.userInfo.ClientId}`,
    },
    // 根据你接口需求自定义body参数
    formData: {},
  },
  formats: 'png,jpg,jpeg,svg,doc,docx,xls,xlsx,pdf',
  // 文件上传大小限制
  size: 10,
  // 文件数量限制
  count: 6,
  // 调试时传true打印日志并且显示file按钮
  debug: false,
  // 选择文件后是否立即自动上传，true=选择后立即上传
  instantly: true,
})

/* 判断文件类型展示不同图片 */
function getFileTypeImage(type) {
  const imgEnum = {
    docx,
    doc,
    xls,
    xlsx,
    jpg,
    jpeg,
    png,
    svg,
    pdf,
    ppt,
    pptx,
  }
  return imgEnum[type]
}

// 移除文件
const handleRemoveFile = (index: number) => {
  model.attachmentList.splice(index, 1)
}

/* 文件预览 */
function handlePreviewFile(file) {
  uni.navigateTo({
    url: `/pages/preview/document?url=${encodeURIComponent(file.attachmentPath)}&name=${encodeURIComponent(file.name)}`,
  })
}

const displayFormat = (items) => {
  console.log('[ items ] 🌸>', items)
  return `${items[0].label}年${items[1].label}月${items[2].label}日 ${items[3].label}:${items[4].label}`
}
/* 转换截止时间为后端需要格式 */
function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:00`
}

// 文件选择回调
function onChange(files, childId) {
  console.log('files===========', files)
  console.log('当前选择的文件列表：', files.values())
  // submitForm.value.files = files
  uni.showToast({
    title: '上传中~',
    icon: 'none',
  })
}

// 某文件上传结束回调(成功失败都回调)
function onUploadEnd(item, childId) {
  console.log('==================', item)
  if (item.responseText) {
    console.log('返回的字符串JSON转Object对象', JSON.parse(item.responseText))
    const responseText = JSON.parse(item.responseText)
    if (responseText.code === 200) {
      model.attachmentList.push({
        name: responseText?.data?.fileName,
        attachmentPath: responseText?.data?.url,
        ossId: responseText?.data?.ossId,
        taskId: state.taskId,
        role: 'teacher',
      })
      console.log('model.attachmentList.===', model.attachmentList)
    }
  }
}

const editYn = ref(false)
const btnText = ref<string>('修改任务')

const form = ref()

/* 获取详情 */
async function getDetails(taskId) {
  const data = await getTaskDetails(taskId)
  nextTick(() => {
    const res = data?.data
    model.taskName = res.taskName
    model.deadline = new Date(res.deadline).getTime()
    model.description = res.description
    model.imgList = res.imgList ? res.imgList.split(',') : []
    model.attachmentList = res.attachmentList ?? []
    model.status = `${res.status}` === '1' ? '开启' : '关闭'
    state.bottomBtnDisabled = `${res.status}` === '0'
  })
}

/* 页面加载时获取数据 */
onLoad(async (query) => {
  state.taskId = query.taskId
  state.courseId = query.courseId
  state.courseName = query.courseName
  await getDetails(state.taskId)
})

/* 修改任务 */
function handleEdit() {
  const bol = btnText.value === '修改任务'
  editYn.value = bol
  btnText.value = bol ? '提交任务' : '修改任务'
  if (editYn.value) {
    model.imgList = model.imgList.map((url) => {
      return {
        url,
      }
    })
    console.log(model.imgList, 'model.imgList - model.imgList')
  }
  if (!bol) {
    form.value
      .validate()
      .then(({ valid, errors }) => {
        if (valid) {
          // showSuccess({
          //   msg: '校验通过',
          // })
          /* 处理图片数组 */
          if (model.imgList.length > 0) {
            model.imgList = model.imgList.map((e) => {
              if (e.response) {
                return JSON.parse(e.response).data.url
              } else {
                return e.url
              }
            })
          }
          model.imgList = model.imgList.length > 0 ? model.imgList.join(',') : ''
          /* 处理时间 */
          model.deadline = formatTimestamp(model.deadline)
          /* 处理 任务设置 */
          model.status = model.status === '开启' ? 1 : 0
          /* 添加 课程名称和课程id */
          model.courseName = state.courseName
          model.courseId = state.courseId
          console.log('[ model ] 🌸>', model)
          updateTaskApi({ ...model, taskId: state.taskId })
        }
      })
      .catch((error) => {
        console.log(error, 'error')
      })
      .finally(() => {
        uni.navigateTo({
          url: `/pages/task/index?courseId=${state.courseId}&courseName=${state.courseName}&taskId=${state.taskId}`,
        })
      })
  }
}
</script>

<style lang="scss" scoped>
/* label */
:deep(.wd-input__label-inner),
:deep(.wd-picker__label),
.task-setting,
:deep(.wd-textarea__label-inner) {
  font-size: 26rpx;
  font-weight: 700;
  color: #3d3d3d;
}

:deep(.wd-input__body),
:deep(.wd-input__inner),
:deep(.wd-picker__placeholder),
:deep(.wd-picker__value),
:deep(.wd-textarea__value) {
  font-size: 22rpx;
  font-weight: 400;
  color: #b2b5bd;
  text-align: right;
}

:deep(.wd-picker__value) {
  margin-right: 0;
}

:deep(.wd-picker__value-wraper .wd-icon-arrow-right) {
  display: none;
}
/* stylelint-disable-next-line selector-type-no-unknown */
:deep(uni-textarea) {
  height: auto !important;
}

:deep(.wd-textarea) {
  flex-direction: column;
  .wd-textarea__value,
  .wd-textarea__inner {
    margin-top: 8rpx;
    color: #999999;
    text-align: left;
  }
}
/* 图片展示 */
.imgList {
  display: grid;
  gap: 10rpx;
  margin: 0 24rpx;
}
.upload {
  margin-top: 20rpx;
  :deep(.wd-upload) {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8rpx 20rpx;
    padding: 20rpx;
  }

  :deep(.wd-upload__preview),
  :deep(.wd-upload__evoke) {
    width: 100%;
    height: 100%;
    aspect-ratio: 1 / 1;
    margin: 0;
  }
}
/* 附件 */
.upload-file {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 40rpx;
  padding: 0 40rpx;

  .item-image {
    width: 150rpx;
    height: 150rpx;
    object-fit: cover;
  }

  .upload-delete {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
  }

  .fileName {
    display: -webkit-box;
    width: 150rpx;
    margin-top: 12rpx;
    overflow: hidden;
    font-size: 22rpx;
    color: #3d3d3d;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

:deep(.wd-icon-close) {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  z-index: 999;
  display: none;
}
.images-hover {
  :deep(.wd-icon-close) {
    display: block;
  }
}
/* 附件 */
.annex {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  font-weight: 700;
  color: #3d3d3d;
}

.annex::before {
  display: inline-block;
  width: 8rpx;
  height: 30rpx;
  margin-right: 12rpx;
  content: '';
  background-color: #3670f7;
}
/* 提交任务 */
.footer {
  width: 90vw;
  padding: 24rpx 0;
  margin-left: 50%;
  margin-top: 30rpx;
  transform: translateX(-50%);

  .wd-button {
    background: linear-gradient(90deg, #0d53ff 2%, #20a4ff 100%);
  }
}
</style>
